<template>
  <h3 style="display: flex">暗灯统计分析:</h3>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
  </el-row>
  <div>
    <div ref="chart" style="height: 500px; width: 1300px"></div>
  </div>
  <div>
    <el-button type="primary" @click="exportToExcel">导出到Excel</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
// import Index from "./views/index/index.vue";
import * as XLSX from 'xlsx'; 

const value2 = ref([]);

const shortcuts = [
  {
    text: "当天",
    value: () => {
      const now = new Date();
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      return [start, now];
    },
  },
  {
    text: "近1周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "近2周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 14);
      return [start, end];
    },
  },
  {
    text: "近1月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); //创建dom引用

const series_data2 = ref();
const series_data = ref();
const series_data1 = ref();

const exportToExcel = () => {
  if (!chart.value) {
    ElMessage.error('图表未初始化');
    return;
  }
  const myChart = echarts.init(chart.value);
  const option = myChart.getOption();
  const startDate = formatDate(value2.value[0]);
  const endDate = formatDate(value2.value[1]);
  const area = value3.value;
  const xAxisData1 = option.xAxis[0].data;
  const xAxisData2 = option.xAxis[0].name;
  const xAxisData = [xAxisData2, ...Array.from(xAxisData1)];
  const seriesData1 = option.series.map(s => s.data);
  const seriesData2 = option.series.map(s => s.name);
  const seriesData = seriesData1.map((data, index) => {
  return [seriesData2[index], ...data];
});
  console.log('y', seriesData)
  console.log('x', xAxisData)
  const ws = XLSX.utils.aoa_to_sheet([xAxisData, ...seriesData]);
  const wb = XLSX.utils.book_new();
  const fileName = `${startDate}_${endDate}_${area}_暗灯统计.xlsx`;
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, fileName);
};

const initChart = async () => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  let option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        // params 是一个数组，包含了所有在当前横坐标上的系列数据
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["呼叫维修", "呼叫班长"],
      orient: "vertical", // 改为垂直显示
      right: 10, // 将图例放置在右侧边缘附近
      top: "middle", // 图例居中对齐
      itemGap: 20, // 图例项之间的间距
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
        custom: {
          show: true,
          title: 'Export to Excel',
          icon: 'file-excel-o', // 使用Font Awesome图标
          onclick: exportToExcel // 绑定到你的导出函数
    }
      },
    },

    title: {
      text: "暗灯统计",
      left: "center",
      textStyle: {
        color: "black", // 设置标题颜色为白色
      },
      subtext: "单位：次",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      name: "工位",
      type: "category",
      data: series_data1.value,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "呼叫班长",
        data: series_data2.value,
        stack: "total",
        type: "bar",
        color: "#59c4e6",
      },
      {
        name: "呼叫维修",
        data: series_data.value,
        stack: "total",
        type: "bar",
        color: "#edafda",
      },
    ],
    dataZoom: [
      {
        type: "slider",
        start: 0,
        end: 100,
      },
      {
        type: "inside",
        start: 90,
        end: 100,
      },
    ],
  };

  myChart.setOption(option);
};

onMounted(() => {
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  value2.value = [todayStart, now];

  use_show_data_in_html();
});

const value3 = ref("装配A");
const router = useRouter();
const options = [
  { value: "装配A", label: "装配A" },
  { value: "装配B", label: "装配B" },
  { value: "缸体M1", label: "缸体M1" },
  { value: "缸体M2", label: "缸体M2" },
  { value: "缸盖M1", label: "缸盖M1" },
  { value: "缸盖M2", label: "缸盖M2" },
  { value: "曲轴M1", label: "曲轴M1" },
];

function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

var construct_url = "";
watch([value2, value3], () => {
  const start_time: Object = formatDate(value2.value[0]);
  const end_time: Object = formatDate(value2.value[1]);
  construct_url = "http://10.64.35.32:8000/man_ana_sql_server/get_andon_call/?" + "start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&sub_area=" + value3.value + "&page_size=" + 10001;
  use_show_data_in_html();
});

const use_show_data_in_html = async () => {
  console.log(construct_url);
  const response = await axios.get(construct_url);
  const data = response.data;
  console.log(data);
  // 初始化数据容器
  series_data1.value = [];
  series_data.value = [];
  series_data2.value = [];

  const dataMap = new Map();

  data.forEach((item) => {
    if (!dataMap.has(item.equipment_id)) {
      dataMap.set(item.equipment_id, { calls: 0, leaders: 0 });
    }

    if (item.call_type === "呼叫维修") {
      dataMap.get(item.equipment_id).calls++;
    } else if (item.call_type === "呼叫班长") {
      dataMap.get(item.equipment_id).leaders++;
    }
  });

  // 将Map转换为数组并排序
  const sortedDataArray = Array.from(dataMap.entries()).sort((a, b) => {
    const totalA = a[1].calls + a[1].leaders;
    const totalB = b[1].calls + b[1].leaders;
    return totalB - totalA; // 降序排序
  });

  // 重新构建series_data1, series_data, and series_data2
  series_data1.value = sortedDataArray.map((entry) => entry[0]); // 设备ID
  series_data.value = sortedDataArray.map((entry) => entry[1].calls); // 呼叫维修次数
  series_data2.value = sortedDataArray.map((entry) => entry[1].leaders); // 呼叫班长次数

  // 更新图表数据
  initChart();
};
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important;
  overflow-y: auto !important;
}
</style>
